package org.jeecg.modules.audit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.http.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.LiveConfig;
import org.jeecg.modules.audit.service.AuditLiveApplyService;
import org.jeecg.modules.live.entity.LiveApply;
import org.jeecg.modules.live.entity.LiveInfo;
import org.jeecg.modules.live.service.ILiveApplyService;
import org.jeecg.modules.live.service.ILiveInfoService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.util.CommonUtil;
import org.jeecg.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;

/**
* @Description: 直播审核
* @Author: jeecg-boot
* @Date:   2020-05-07
* @Version: V1.0
*/
@Slf4j
@Api(tags="直播审核")
@RestController
@RequestMapping("/audit/live/liveApply")
public class AuditLiveApplyController extends JeecgController<LiveApply, ILiveApplyService> {
   @Autowired
   private AuditLiveApplyService auditLiveApplyService;
    @Autowired
    private ILiveApplyService liveApplyService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ILiveInfoService liveInfoService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private LiveConfig liveConfig;
   /**
    * 分页列表查询
    *
    * @param
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "直播申请-分页列表查询")
   @ApiOperation(value="直播申请-分页列表查询", notes="直播申请-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(@RequestParam(name="applyAccountNickName",required=false) String applyAccountNickName,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  @RequestParam(name="realName",required=false)String realName,
                                  HttpServletRequest req) {

//        //获取当前用户
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        //检查用户有没有权限
//        Map<String,String> roleMap = sysUserRoleService.querySingleUserRole(sysUser.getId());
//        boolean isAuthor = CommonUtil.checkUserRole(roleMap,"直播审核权限");
//        if(!isAuthor){
//            Result.error("您没有直播审核权限！");
//        }
       QueryWrapper<LiveApply> queryWrapper = new QueryWrapper<LiveApply>();
       queryWrapper.like(!StringUtil.isEmpty(applyAccountNickName),"apply_account_nick_name",applyAccountNickName);
       queryWrapper.like(!StringUtil.isEmpty(realName),"real_name",realName);
       queryWrapper.orderByDesc("apply_time");
       Page<LiveApply> page = new Page<LiveApply>(pageNo, pageSize);
       IPage<LiveApply> pageList = liveApplyService.page(page, queryWrapper);
       List<LiveApply> records = pageList.getRecords();
       //设置审核昵称 申请人账号昵称
       records.forEach(item->{
           SysUser sysUser = sysUserService.getById(item.getExamineUser());
           if(null != sysUser){
               item.setExamineUserName(sysUser.getRealname());
           }else{
               item.setExamineUserName("");
           }
       });
       return Result.ok(pageList);
   }



    /**
     * 审核通过-直播审核
     *
     * @param liveApply
     * @return
     */
    @AutoLog(value = "直播审核-发布 和添加直播信息")
    @ApiOperation(value="直播审核-发布", notes="直播审核-发布")
    @PutMapping(value = "/auditLiveApplyRelease")
    public Result<?> auditLiveApplyRelease(@RequestBody LiveApply liveApply) {

        if(null == liveApply){
            return Result.error("发布失败,参数liveApply信息为空！");
        }

        //获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String pushUrl;// 直播推流地址
        String broadcastUrl;// 直播播放地址
        String streamId; // 流id
        String authorityKey; // 鉴权 Key
        // 1 ：申请直播永久有效
        if(1 == liveApply.getIsNeverExpires()){

//			 //一个用户只能审核通过一次永久权限直播
//			 QueryWrapper<LiveInfo> queryWrapper = new QueryWrapper<LiveInfo>();
//			 queryWrapper.eq("user_id", liveApply.getUserId());
//			 queryWrapper.notIn("live_status", 3);
//			 queryWrapper.eq("live_end_time", DateUtils.str2Date("2999-12-30 00:00:00",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));//直播是否永久有效 1 永久有效
//			 List<LiveInfo> list = liveInfoService.list(queryWrapper);
//			 if(null != list && list.size() > 0){
//				 return Result.error("用户已经有永久权限！");
//			 }

            String txTime ="73c5250c";
           int ran2 = (int) (Math.random()*1000);
           streamId = liveApply.getUserId()+"A"+ran2;
           String txSecret = CommonUtil.getSafeUrl(liveConfig.getPushKey(),streamId,txTime);
            pushUrl = "rtmp://"+
                    liveConfig.getPushDomainName()+"/"+
                    liveConfig.getAppName()+"/"+
                    streamId+"?"+txSecret;
            broadcastUrl = "http://"+
                    liveConfig.getBroadcastDomainName()+"/"+
                    liveConfig.getAppName()+"/"+
                    streamId+".flv?"+txSecret;
        }else {
            String txTime ="73c5250c";
            int ran2 = (int) (Math.random()*1000);
            streamId = liveApply.getUserId()+liveApply.getExpiresEndTime().getTime()+"A"+ran2;
            String txSecret = CommonUtil.getSafeUrl(liveConfig.getPushKey(),streamId,txTime);
            pushUrl = "rtmp://"+
                    liveConfig.getPushDomainName()+"/"+
                    liveConfig.getAppName()+"/"+
                    streamId+"?"+txSecret;
            broadcastUrl = "http://"+
                    liveConfig.getBroadcastDomainName()+"/"+
                    liveConfig.getAppName()+"/"+
                    streamId+".flv?"+txSecret;
        }
        liveApply.setApplyStatus(1);// 1:通过
        liveApply.setExamineUser(sysUser.getId());//审核人
        liveApply.setExamineTime(DateUtils.getDate());//审核时间

        LiveInfo liveInfo = new LiveInfo();
//		 liveInfo.setCreateBy(liveApply.getCreateBy());
        liveInfo.setCreateTime(DateUtils.getDate());
        liveInfo.setUserId(liveApply.getUserId());
        long startTime = liveApply.getExpiresStartTime().getTime();
        long endTime = liveApply.getExpiresEndTime().getTime();
        long nowTime = DateUtils.getDate().getTime();
        liveInfo.setLiveStatus(1);//直播状态 0：直播中 1：直播未开始 2：直播结束 3：直播强制终止
        if(nowTime < startTime){
            liveInfo.setLiveStatus(1);
        }
        if(nowTime > startTime && nowTime < endTime){
            liveInfo.setLiveStatus(0);
        }
        if(nowTime > endTime){
            liveInfo.setLiveStatus(2);
        }
        liveInfo.setLiveStartTime(liveApply.getExpiresStartTime());
        liveInfo.setLiveEndTime(liveApply.getExpiresEndTime());
        liveInfo.setPushUrl(pushUrl);
        liveInfo.setBroadcastUrl(broadcastUrl);
        liveInfo.setStreamId(streamId);
        try{
            auditLiveApplyService.auditLiveApproved(liveApply,liveInfo);
            return Result.ok("审核通过，发布成功!");
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("发布失败：" + e.getMessage());
        }
    }

    /**
     * 驳回
     *
     * @param liveApply
     * @return
     */
    @AutoLog(value = "直播审核-驳回")
    @ApiOperation(value="直播审核-驳回", notes="直播审核-驳回")
    @PutMapping(value = "/auditLiveApplyReject")
    public Result<?> auditLiveApplyReject(@RequestBody LiveApply liveApply) {

        if(null == liveApply){
            return Result.error("无效参数！参数 liveApply 信息为空！");
        }
        //获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        liveApply.setApplyStatus(2);// 申请状态 0：申请中 1：审核通过 2：审核不通过 3：重新申请中
        liveApply.setExamineUser(sysUser.getId());//审核人
        liveApply.setExamineTime(DateUtils.getDate());//审核时间
        try {

            //清楚liveInfo
            QueryWrapper<LiveInfo> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("user_id",liveApply.getUserId());
            liveInfoService.remove(deleteWrapper);
            if(liveApplyService.updateById(liveApply)){
               return Result.ok("驳回成功!");
           }
            return Result.error("驳回失败!");
        }catch(Exception e){
            log.error(e.getMessage(), e);
            return Result.error("驳回失败：" + e.getMessage());
        }
    }


    /**
     * 批量 审核通过-直播审核
     *
     * @param liveApplyList
     * @return
     */
    @AutoLog(value = "批量直播审核-发布 和添加直播信息")
    @ApiOperation(value="批量直播审核-发布", notes="批量直播审核-发布")
    @PutMapping(value = "/auditBatchLiveApplyRelease")
    public Result<?> auditBatchLiveApplyRelease(@RequestBody List<LiveApply> liveApplyList) {

        if(null == liveApplyList || liveApplyList.size() <= 0){
            return Result.error("发布失败,参数liveApplyList信息为空！");
        }
        //获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String pushUrl;// 直播推流地址
        String broadcastUrl;// 直播播放地址
        String streamId; // 流id
        String authorityKey; // 鉴权 Key
        List<LiveInfo> liveInfoList = null;
        for (LiveApply liveApply : liveApplyList) {
            // 1 ：申请直播永久有效
            if("1".equals(liveApply.getIsNeverExpires())){

                //一个用户只能审核通过一次永久权限直播
                QueryWrapper<LiveInfo> queryWrapper = new QueryWrapper<LiveInfo>();
                queryWrapper.eq("user_id", liveApply.getUserId());
                queryWrapper.notIn("live_status", 3);
                queryWrapper.eq("live_end_time", DateUtils.str2Date("2999-12-30 00:00:00",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));//直播是否永久有效 1 永久有效
                List<LiveInfo> list = liveInfoService.list(queryWrapper);
                if(null != list && list.size() > 0){
                    return Result.error("用户已经有永久权限！");
                }
                String txTime ="73c5250c";
                int ran2 = (int) (Math.random()*1000);
                streamId = liveApply.getUserId()+"A"+ran2;
                String txSecret = CommonUtil.getSafeUrl(liveConfig.getPushKey(),streamId,txTime);
                pushUrl = "rtmp://"+
                        liveConfig.getDomain()+
                        liveConfig.getAppName()+
                        streamId+"?"+txSecret;
                broadcastUrl = "http://"+
                        liveConfig.getDomain()+
                        liveConfig.getAppName()+
                        streamId+".flv?"+txSecret;
            }else {
                String txTime ="73c5250c";
                int ran2 = (int) (Math.random()*1000);
                streamId = liveApply.getUserId()+liveApply.getExpiresEndTime().getTime()+"A"+ran2;
                String txSecret = CommonUtil.getSafeUrl(liveConfig.getPushKey(),streamId,txTime);
                pushUrl = "rtmp://"+
                        liveConfig.getDomain()+
                        liveConfig.getAppName()+
                        streamId+
                        "?"+txSecret;
                broadcastUrl = "http://"+
                        liveConfig.getDomain()+
                        liveConfig.getAppName()+
                        streamId+
                        ".flv?"+txSecret;
            }
            liveApply.setApplyStatus(1);// 1:通过
            liveApply.setExamineUser(sysUser.getId());//审核人
            liveApply.setExamineTime(DateUtils.getDate());//审核时间

            LiveInfo liveInfo = new LiveInfo();
            liveInfo.setCreateBy(liveApply.getCreateBy());
            liveInfo.setCreateTime(DateUtils.getDate());
            liveInfo.setUserId(liveApply.getUserId());
            long startTime = liveApply.getExpiresStartTime().getTime();
            long endTime = liveApply.getExpiresEndTime().getTime();
            long nowTime = DateUtils.getDate().getTime();
            liveInfo.setLiveStatus(1);//直播状态 0：直播中 1：直播未开始 2：直播结束 3：直播强制终止
            if(nowTime < startTime){
                liveInfo.setLiveStatus(1);
            }
            if(nowTime > startTime && nowTime < endTime){
                liveInfo.setLiveStatus(0);
            }
            if(nowTime > endTime){
                liveInfo.setLiveStatus(2);
            }
            liveInfo.setLiveStartTime(liveApply.getExpiresStartTime());
            liveInfo.setLiveEndTime(liveApply.getExpiresEndTime());
            liveInfo.setPushUrl(pushUrl);
            liveInfo.setBroadcastUrl(broadcastUrl);
            liveInfoList.add(liveInfo);
        }
        try{
            auditLiveApplyService.auditBatchLiveApproved(liveApplyList,liveInfoList);
            return Result.ok("批量审核通过，发布成功!");
        }catch (Exception e){
            log.error(e.getMessage(), e);
            return Result.error("批量发布失败：" + e.getMessage());
        }
    }

    /**
     * 批量 驳回
     *
     * @param liveApplyList
     * @return
     */
    @AutoLog(value = "批量直播审核-驳回")
    @ApiOperation(value="批量直播审核-驳回", notes="批量直播审核-驳回")
    @PutMapping(value = "/auditBatchLiveApplyReject")
    public Result<?> auditBatchLiveApplyReject(@RequestBody List<LiveApply> liveApplyList) {

        if(null == liveApplyList || liveApplyList.size() <= 0){
            return Result.error("无效参数！参数 liveApply 信息为空！");
        }
        //获取当前用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        for (LiveApply liveApply : liveApplyList) {
            liveApply.setApplyStatus(2);// 申请状态 0：申请中 1：审核通过 2：审核不通过 3：重新申请中
            liveApply.setExamineUser(sysUser.getId());//审核人
            liveApply.setExamineTime(DateUtils.getDate());//审核时间
        }

        try {
            if(liveApplyService.updateBatchById(liveApplyList)){
               return Result.ok("批量驳回成功!");
           }
            return Result.error("批量驳回失败!");
        }catch(Exception e){
            log.error(e.getMessage(), e);
            return Result.error("批量驳回失败：" + e.getMessage());
        }
    }


    /**
     * 通过id查询 审核状态
     *
     * @param id
     * @return
     */
    @AutoLog(value = "直播申请状态查询-通过id查询")
    @ApiOperation(value="直播申请状态查询-通过id查询", notes="直播申请状态查询-通过id查询")
    @GetMapping(value = "/queryByIdIsOauth")
    public Result<?> queryByIdIsOauth(@RequestParam(name="id",required=true) String id) {

        if(StringUtils.isEmpty(id)){
            return Result.error("参数 id 为空！");
        }
        LiveApply liveApply = liveApplyService.getById(id);
        if(null == liveApply){
            return Result.error("未查询到申请信息！");
        }
        return Result.ok(liveApply);
    }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "直播申请-通过id查询")
   @ApiOperation(value="直播申请-通过id查询", notes="直播申请-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       LiveApply liveApply = liveApplyService.getById(id);
       return Result.ok(liveApply);
   }


}
